package com.studysystem.controller;

import com.studysystem.dto.CourseModuleDTO;
import com.studysystem.dto.CourseContentDTO;
import com.studysystem.entity.Course;
import com.studysystem.entity.CourseContent;
import com.studysystem.entity.CourseModule;
import com.studysystem.repository.CourseContentRepository;
import com.studysystem.repository.CourseRepository;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/learning")
public class CourseLearningController {
    private final CourseRepository courseRepository;
    private final CourseContentRepository courseContentRepository;

    public CourseLearningController(CourseRepository courseRepository, CourseContentRepository courseContentRepository) {
        this.courseRepository = courseRepository;
        this.courseContentRepository = courseContentRepository;
    }

    // 获取课程所有模块和内容
    @GetMapping("/courses/{courseId}/modules")
    public List<CourseModuleDTO> getCourseModules(@PathVariable Long courseId) {
        Course course = courseRepository.findById(courseId).orElse(null);
        if (course == null) return null;
        return course.getModules().stream().map(this::toModuleDTO).collect(Collectors.toList());
    }

    // 获取单个内容详情
    @GetMapping("/contents/{contentId}")
    public CourseContentDTO getContentDetail(@PathVariable Long contentId) {
        return courseContentRepository.findById(contentId).map(this::toContentDTO).orElse(null);
    }

    private CourseModuleDTO toModuleDTO(CourseModule module) {
        CourseModuleDTO dto = new CourseModuleDTO();
        dto.setId(module.getId());
        dto.setTitle(module.getTitle());
        dto.setDescription(module.getDescription());
        dto.setOrderNumber(module.getOrderNumber());
        dto.setContents(module.getContents().stream().map(this::toContentDTO).collect(Collectors.toList()));
        return dto;
    }

    private CourseContentDTO toContentDTO(CourseContent content) {
        CourseContentDTO dto = new CourseContentDTO();
        dto.setId(content.getId());
        dto.setTitle(content.getTitle());
        dto.setDescription(content.getDescription());
        dto.setType(content.getType().name());
        dto.setContentUrl(content.getContentUrl());
        dto.setDuration(content.getDuration());
        dto.setOrderNumber(content.getOrderNumber());
        return dto;
    }
} 